package org.springframework.extend.persistence;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.extend.persistence.repository.PersistenceRepository;
import org.springframework.extend.persistence.repository.SqlResource;

@Aspect
public class PersistenceContainer {

	private static final int		QUERY_ID_INDEX	= 0;

	private PersistenceRepository	repository;

	public Object proceedRequest(ProceedingJoinPoint pjp) throws Throwable {

		Object firstArg = pjp.getArgs()[QUERY_ID_INDEX];

		// sql operation with sql parameter
		if (String.class.getName().equals(firstArg.getClass().getName())) {
			// extract query id
			String queryId = (String) firstArg;

			// find sql at Persistence repository
			SqlResource resource = repository.findSqlResource(queryId);

			Object[] newArgs = injectQuery(resource, pjp.getArgs());

			Object retVal = pjp.proceed(newArgs);

			return retVal;
		}

		// not sql operation with sql parameter
		return pjp.proceed();

	}

	private Object[] injectQuery(SqlResource resource, Object[] oldArgs) {
		int argsLength = oldArgs.length;
		Object[] newArgs = new Object[argsLength];

		for (int index = 0; index < argsLength; index++) {
			if (index == QUERY_ID_INDEX) {
				newArgs[index] = resource.getSql();
			} else {
				newArgs[index] = oldArgs[index];
			}
		}
		return newArgs;
	}

	public void setRepository(PersistenceRepository repository) {
		this.repository = repository;
	}

	public PersistenceRepository getRepository() {
		return repository;
	}
}
